package com.dpxm.zdbdg.charts.shuangseqiu.service;


import com.alibaba.fastjson.JSONObject;
import com.dpxm.zdbdg.charts.shuangseqiu.dao.ShuangSeQiuDao;
import com.dpxm.zdbdg.charts.shuangseqiu.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import vehiclebase.enums.QueryEnum;
import vehiclebase.utils.ToolsUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ShuangSeQiuService {
    @Autowired
    private ShuangSeQiuDao shuangSeQiuDao;
    /**
     * 分析冷热号
     * @return
     */
    public coldHotRes coldHot() throws IOException {
        coldHotRes coldHot = new coldHotRes();
        //平台对象
        PtQueryShuangSeQiuVO ptQueryDaLe = new PtQueryShuangSeQiuVO();


        RestTemplate restTemplate = new RestTemplate();
        BufferedReader reader = null;
        String uuu = "http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=2000";
        HttpURLConnection connection = null;
        URL url = new URL(uuu);
        String line = "";
        // 根据URL生成HttpURLConnection
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");// 默认GET请求
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
        connection.setRequestProperty("Accept","application/json;charset=UTF-8");
//            connection.setRequestProperty("Accept-Encoding","gzip, deflate");
//            connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
        connection.setRequestProperty("Cache-Control","max-age=0");
        connection.setRequestProperty("Connection","keep-alive");
        connection.setRequestProperty("Cookie","HMF_CI=44ec7e8f3ae4965c4c5f1340aea797370b53a038a32ee289fff6471f8a8dd8d47e");
        connection.setRequestProperty("Host","www.cwl.gov.cn");
        connection.setRequestProperty("Upgrade-Insecure-Requests","1");
        connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36");
        connection.connect();// 建立TCP连接
        int type = connection.getResponseCode();
        if (type == HttpURLConnection.HTTP_OK) {
//                 发送http请求
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        }
        StringBuilder result = new StringBuilder();
        // 循环读取流
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

       // reader.close();
       String sad=result.toString();
        //将平台的数据转化为自有对象
        ptQueryDaLe = JSONObject.parseObject(sad, PtQueryShuangSeQiuVO.class);
        List<QueryShuangSeQiuVO> queryShuangSeQiuVOList = new ArrayList<>();
        if(ToolsUtils.notEmpty(ptQueryDaLe) && ptQueryDaLe.getMessage().equals("查询成功")){
            Values valueList = ptQueryDaLe.getResult().get(0);
            //将数据存入本地库
            if(ToolsUtils.notEmpty(valueList)){
              //  valueList.forEach(a->{
                    QueryShuangSeQiuVO queryDaLeTouVO = new QueryShuangSeQiuVO();
                    queryDaLeTouVO.setQihao(valueList.getCode());
                    queryDaLeTouVO.setH_one(Integer.parseInt(valueList.getBlue()));
                    queryDaLeTouVO.setWeek(valueList.getWeek());
                    List<String> listnHong = Arrays.asList(valueList.getRed().split(","));
                    //List<String> 转化为List<Integer>
                    List<Integer> listNumbeInsr = listnHong.stream().map(Integer::parseInt).collect(Collectors.toList());
                    queryDaLeTouVO.setQ_one(listNumbeInsr.get(0));
                    queryDaLeTouVO.setQ_two(listNumbeInsr.get(1));
                    queryDaLeTouVO.setQ_three(listNumbeInsr.get(2));
                    queryDaLeTouVO.setQ_four(listNumbeInsr.get(3));
                    queryDaLeTouVO.setQ_five(listNumbeInsr.get(4));
                    queryDaLeTouVO.setQ_six(listNumbeInsr.get(5));
                    queryDaLeTouVO.setCreatedate(valueList.getDate().substring(0,10));
                    queryShuangSeQiuVOList.add(queryDaLeTouVO);
              //  });
                if(ToolsUtils.notEmpty(queryShuangSeQiuVOList)){
                    //将数据存入库
                    QueryShuangSeQiuVO queryShuangSeQiuVO = shuangSeQiuDao.QueryDangQi(queryShuangSeQiuVOList.get(0).getQihao());
                    if (ToolsUtils.isEmpty(queryShuangSeQiuVO)){
                        shuangSeQiuDao.saveShuangSeQiu(queryShuangSeQiuVOList);
                    }
                }
            }
        }


        //查询出最近16期开奖信息
        List<QueryShuangSeQiuVO> queryMessage = shuangSeQiuDao.QueryMessage(QueryEnum.QUERY_QIHAO.val());
        List<Integer> hong = new ArrayList<>();
        //此集合为16期内的所有开奖号码。 16期内出险过4次的号码为热号
        if(ToolsUtils.notEmpty(queryMessage)){
            queryMessage.forEach(a->{
                hong.add(a.getQ_one());
                hong.add(a.getQ_two());
                hong.add(a.getQ_three());
                hong.add(a.getQ_four());
                hong.add(a.getQ_five());
            });
        }
        //热号分析 （16期内出现过4次及的号码为热号）
        getHotNumb(hong,coldHot);
        //冷号分析 （16期没有出现过的号码冷号）
        getCotNumb(hong,coldHot);
        //组装返回的数据
        getMessage(coldHot);
        return coldHot;
    }

    /**
     * 组装返回的数据
     * @param coldHot
     * @return
     */
    public void  getMessage(coldHotRes coldHot){
        //冷号
        StringBuffer coldNumber = new StringBuffer();
        coldNumber.append("本期推荐冷号：");
        List<String> coldList = coldHot.getColdNumber();
        for (int i=0 ;i<coldList.size() ; i++){
            coldNumber.append(" "+coldList.get(i));
        }

        //热号
        StringBuffer hotNumber = new StringBuffer();
        hotNumber.append("本期推荐热号：");
        List<String> hotList = coldHot.getHotNumber();
        for (int i=0 ;i<hotList.size() ; i++){
            hotNumber.append(" "+hotList.get(i));
        }

        //调整红球的格式
        StringBuffer Number = new StringBuffer();

        //机选五注
        for (int k=0 ;k<5 ; k++){
            //机选 冷号
            Random random = new Random();
            int num = random.nextInt(coldList.size());

            System.out.println(coldList.get(num));
            //机选 热号
            List<String> jxHotNumber = new ArrayList<>();
            for (int i=0 ;i<50 ; i++){
                Random randomss = new Random();
                int nums = randomss.nextInt(hotList.size());
                String shu=hotList.get(nums);
                //判断jxHotNumber是否含有shu
                if (jxHotNumber.stream().filter(w->String.valueOf(w.toString()).equals(shu)).findAny().isPresent()){
                    continue;
                }
                jxHotNumber.add(shu);
               // System.out.println(jxHotNumber.toString());
                if(jxHotNumber.size()==5){
                    break;
                }
            }
            //把冷号也放进去
            jxHotNumber.add(coldList.get(num));
            //机选两位篮球
            List<String> modes = new ArrayList<>();
            for (int i=1; i<=16; i++){ //模拟1-16
                modes.add(String.valueOf(i));
            }
            //最终篮球的号码
            List<String> jxLanHotNumber = new ArrayList<>();
            for (int i=0 ;i<20 ; i++){
                Random randomss = new Random();
                int nums = randomss.nextInt(modes.size());
                String shu=modes.get(nums);
                if (jxLanHotNumber.stream().filter(w->String.valueOf(w.toString()).equals(shu)).findAny().isPresent()){
                    continue;
                }
                jxLanHotNumber.add(shu);
                if(jxLanHotNumber.size()==1){
                    break;
                }
            }
            //List<String> 转化为List<Integer>
            List<Integer> codesInteger = jxHotNumber.stream().map(Integer::parseInt).collect(Collectors.toList());
            //排序
            Collections.sort(codesInteger);
            //最终的红球
            List<String> cotNumbs = codesInteger.stream().map(String::valueOf).collect(Collectors.toList());
            //List<String> 转化为List<Integer>
            List<Integer> codesIntegerlanqiu = jxLanHotNumber.stream().map(Integer::parseInt).collect(Collectors.toList());
            //排序
            Collections.sort(codesIntegerlanqiu);
            //最终的篮球
            List<String> lanqiu = codesIntegerlanqiu.stream().map(String::valueOf).collect(Collectors.toList());
            Number.append("第"+k+"注: ");
            for (int i=0 ;i<cotNumbs.size() ; i++){
                Number.append(cotNumbs.get(i)+" ");
            }
            Number.append(" + ");
            for (int j=0 ;j<lanqiu.size() ; j++){
                Number.append(lanqiu.get(j)+" ");
            }
            Number.append(" | ");

        }

        coldHot.setNumbers(Number.toString());
        coldHot.setBenqiColdNumber(coldNumber.toString());
        coldHot.setBenqiHotNumber(hotNumber.toString());
    }

    /**
     * 冷号分析
     * @param hong
     * @param coldHot
     * @return
     */
    public void getCotNumb(List<Integer> hong,coldHotRes coldHot){
        //冷号需要先去重复
        List<Integer> cotList=hong.stream().distinct().collect(Collectors.toList());
        //排序
        Collections.sort(cotList);
        //List<Integer> 转化为List<String>
        List<String> string2 = cotList.stream().map(String::valueOf).collect(Collectors.toList());
        List<String> modes = new ArrayList<>();
        for (int i=1; i<=33; i++){ //模拟1-33
            modes.add(String.valueOf(i));
        }
        // 平台有，业务表没有
        List<String> cotNumb = modes.stream().filter(a->!string2.contains(a)).collect(Collectors.toList());
        //List<String> 转化为List<Integer>
        List<Integer> codesInteger = cotNumb.stream().map(Integer::parseInt).collect(Collectors.toList());
        //排序
        Collections.sort(codesInteger);
        List<String> cotNumbs = codesInteger.stream().map(String::valueOf).collect(Collectors.toList());
        coldHot.setColdNumber(cotNumbs);
    }

    /**
     * 热号分析
     * @param hong
     * @param coldHot
     * @return
     */
    public void  getHotNumb(List<Integer> hong,coldHotRes coldHot){
        Map<Integer,Integer> map = new HashMap<>();
        for(Integer str:hong){
            Integer i = 1; //定义一个计数器，用来记录重复数据的个数
            if(map.get(str) != null){
                i=map.get(str)+1;
            }
            map.put(str,i);
        }
        // System.out.println("重复数据的个数："+map.toString());
        //热号的集合
        List<Integer> hotNumb = new ArrayList<>();

        //16期内出险过4次及的号码为热号
        for (Integer key : map.keySet()) {
            if(map.get(key) >=4){
                hotNumb.add(key);
            }
        }
        //排序
        Collections.sort(hotNumb);
        //List<Integer> 转化为List<String>
        List<String> hotNumbs = hotNumb.stream().map(String::valueOf).collect(Collectors.toList());
        coldHot.setHotNumber(hotNumbs);
    }

    /**
     * 双色球首页查询号码
     * */
    public List<ShuangSeQiuStringVO> selectShuangSeQiuVO(String qishu)  {
        List<ShuangSeQiuStringVO> queryShuangSeQiuStringVOList = new ArrayList<>();
        //查询大乐透信息

        if(ToolsUtils.notEmpty(qishu)){
            List<QueryShuangSeQiuVO>  query = shuangSeQiuDao.QueryMessage(qishu);
            query.forEach(a->{
                ShuangSeQiuStringVO  queryShuangSeQiuVO = new ShuangSeQiuStringVO();
                queryShuangSeQiuVO.setQihao(a.getQihao());
                queryShuangSeQiuVO.setCreatedate(a.getCreatedate());
                if( a.getQ_one().toString().length()==1){
                    queryShuangSeQiuVO.setQ_one("0"+a.getQ_one().toString());
                }else {
                    queryShuangSeQiuVO.setQ_one(a.getQ_one().toString());
                }
                if( a.getQ_two().toString().length()==1){
                    queryShuangSeQiuVO.setQ_two("0"+a.getQ_two().toString());
                }else {
                    queryShuangSeQiuVO.setQ_two(a.getQ_two().toString());
                }
                if( a.getQ_three().toString().length()==1){
                    queryShuangSeQiuVO.setQ_three("0"+a.getQ_three().toString());
                }else {
                    queryShuangSeQiuVO.setQ_three(a.getQ_three().toString());
                }
                if( a.getQ_four().toString().length()==1){
                    queryShuangSeQiuVO.setQ_four("0"+a.getQ_four().toString());
                }else {
                    queryShuangSeQiuVO.setQ_four(a.getQ_four().toString());
                }
                if( a.getQ_five().toString().length()==1){
                    queryShuangSeQiuVO.setQ_five("0"+a.getQ_five().toString());
                }else {
                    queryShuangSeQiuVO.setQ_five(a.getQ_five().toString());
                }
                if( a.getQ_six().toString().length()==1){
                    queryShuangSeQiuVO.setQ_six("0"+a.getQ_six().toString());
                }else {
                    queryShuangSeQiuVO.setQ_six(a.getQ_six().toString());
                }
                if( a.getH_one().toString().length()==1){
                    queryShuangSeQiuVO.setH_one("0"+a.getH_one().toString());
                }else {
                    queryShuangSeQiuVO.setH_one(a.getH_one().toString());
                }
                queryShuangSeQiuStringVOList.add(queryShuangSeQiuVO);
            });
        }
        return  queryShuangSeQiuStringVOList ;
    }
}
